﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using Webcar.BLL;
using Webcar.Entitys;
using Webcar.Utils;
namespace Webcar.Controllers
{
    public class FileController : BaseControler
    {
        public ActionResult List()
        {
            return View();
        }
        public ActionResult ListPartialView()
        {
            return PartialView();
        }
        public ActionResult ViewList()
        {
            return View();
        }
        public ActionResult ViewListPartialView()
        {
            return PartialView();
        }
        [HttpGet]
        public ActionResult View(int id)
        {
            var model = WebcarDataProvider.DB.user_view_response.Find("file", id, CurrentUser.LoginUserID);
            if (model == null)
            {
                model = new user_view_response();
                model.response_note = "已阅";
                model.table_id = id;
            }
            return View("View",model);
        }
        [HttpPost]
        public ActionResult View(user_view_response model)
        {
            using (var DB = new WebcarContext())
            {
                var exists = DB.user_view_response.Find("file", model.table_id, CurrentUser.LoginUserID);
                if (exists == null)
                {
                    var item = new user_view_response();
                    item.table_id = model.table_id;
                    item.table_name = "file";
                    item.opercode = CurrentUser.LoginUserID;
                    item.response_note = model.response_note;
                    item.response_date = DateTime.Now;
                    DB.user_view_response.Add(item);
                }
                else
                {
                    exists.response_note = model.response_note;
                }
                DB.SaveChanges();
            }
            return RedirectToAction("List");
        }

        public ActionResult New(string file_type)
        {
            bs_files model = new bs_files();
            model.file_type = file_type.IsNull("FILE");
            return View(model:model);
        }
        [HttpPost]
        public ActionResult New(bs_files model)
        {
            CurrentUser.EnsurePermission(PermissionManager.上传文件);
            string filename = Request.Files.UploadFile();
            if(filename.IsNull())
            {
                throw new Exception("未找到上传的文件，文件为空。");
            }
            
                using (var DB = new WebcarContext())
                {
                    model.FileName = filename;
                    model.FileDate = DateTime.Now;
                    model.Oper_Code = CurrentUser.LoginUserID;
                    model.FileLen = Request.Files[0].ContentLength;
                    if (model.FileName2.IsNull())
                        model.FileName2 = model.FileName;
                    if (model.file_type.IsNull())
                        model.file_type = "FILE";
                    DB.bs_files.Add(model);
                    DB.SaveChanges();
                    user_view_response response = new user_view_response();

                    response.opercode = CurrentUser.LoginUserID;
                    response.response_date = DateTime.Now;
                    response.response_note = "已阅";
                    response.table_name = "file";
                    response.table_id = model.FileId;
                    DB.user_view_response.Add(response);
                    DB.SaveChanges();
                }
            return RedirectToAction("List", "File", new {id=model.file_type });
        }
        public ActionResult Delete(int id)
        {
            CurrentUser.EnsurePermission(PermissionManager.上传文件);
            using (var DB = new WebcarContext())
            {
                var model = DB.bs_files.Find(id);
                if (model != null)
                {
                    DB.bs_files.Remove(model);
                    DB.SaveChanges();
                }
            }
            return RedirectToAction("List", "File");
            //return View("List");
            //return Success("List", "File");
        }
        public ActionResult DownloadGsFile(string id)
        {
            // 检查请求下载文件的有效性
            string pfn = Server.MapPath("~/gs_file/" + id);
            if (!System.IO.File.Exists(pfn))
            {
                throw new ArgumentException("无效文件，文件不存在!");
            }
            // 字节流返回文件结果给视图
            return new FilePathResult(pfn,"text/plain");
        }
        public ActionResult Download(int id)
        {
            var file = WebcarDataProvider.DB.bs_files.Find(id);
            if (file == null)
            {
                throw new ArgumentException("无效文件，文件不存在!");
            }

            // 检查请求下载文件的有效性
            string pfn = Server.MapPath("~/files/" + file.FileName);
            if (!System.IO.File.Exists(pfn))
            {
                throw new ArgumentException("无效文件，文件不存在!");
            }
            // 字节流返回文件结果给视图
            var result = new FilePathResultStupidIE(pfn, FileUploadHelper.GetContentType(file.FileName));

            result.FileDownloadName = Path.ChangeExtension(file.FileName2, Path.GetExtension(file.FileName));
            
            return result;
        }
    }

    public class FilePathResultStupidIE : FilePathResult //yeah, maybe i am not totally "politically correct", but still...
    {
        public FilePathResultStupidIE(string fileContents, string contentType) : base(fileContents, contentType) { }

        public override void ExecuteResult(ControllerContext context)
        {
            var b = context.HttpContext.Request.Browser;
            if (b != null && b.Browser.Equals("ie", StringComparison.OrdinalIgnoreCase) && b.MajorVersion <= 8)
            {
                context.HttpContext.Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlPathEncode(base.FileDownloadName) + "\"");
                WriteFile(context.HttpContext.Response);
            }
            else
            {
                base.ExecuteResult(context);
            }
        }
    }
}